<?php
namespace app\shop\controller;
use app\ApiRest;
use app\helppay\model\Helppay;
use app\helppay\model\HelppayConfig;
use app\integral\info\PermissionIntegral;
use app\integral\model\Integral;
use app\member\model\DiscountGoods;
use app\member\model\Goods;
use app\member\model\Member;
use app\member\model\StoredOrder;
use app\shop\model\BargainAtv;
use app\shop\model\BargainRecord;
use app\shop\model\ExpressOrder;
use app\shop\model\GoodsWholesale;
use app\shop\model\TmplConfig;
use think\App;
use think\facade\Cache;
use think\facade\Db;
use app\shop\model\IndexShopOrder as OrderModel;
use app\shop\model\IndexUserInfo;
use app\shop\model\IndexGoods;
use app\shop\model\IndexShopSpePrice;
use app\shop\model\IndexAddress;
use app\shop\model\IndexShopOrderGoods;
use app\shop\model\IndexCouponRecord;
use app\shop\model\IndexShopCollageList;
use app\shop\model\IndexUserCollage;
use app\shop\model\IndexSellingWater;
use app\shop\model\IndexSellingProfit;
use app\shop\model\IndexUser;
use app\shop\model\IndexShopCollage;
use app\shop\model\IndexOrderRefund;
use app\shop\model\IndexCardCount;
use app\shop\model\IndexShopCar;

class IndexShopOrder extends ApiRest{

    protected $model;
    protected $user_info_model;
    protected $goods_model;
    protected $spe_price_model;
    protected $address_model;
    protected $order_goods_model;
    protected $coupon_record_model;
    protected $app;
    protected $collage_list_model;
    protected $user_collage_model;
    protected $water_model;
    protected $profit_model;
    protected $user_model;
    protected $collage_model;
    protected $refund_model;
    protected $count_model;
    protected $car_model;
    public function __construct(App $app) {
        parent::__construct($app);
        $this->app = $app;
        $this->model              = new OrderModel();
        $this->user_info_model    = new IndexUserInfo();
        $this->goods_model        = new IndexGoods();
        $this->spe_price_model    = new IndexShopSpePrice();
        $this->address_model      = new IndexAddress();
        $this->order_goods_model  = new IndexShopOrderGoods();
        $this->coupon_record_model= new IndexCouponRecord();
        $this->collage_list_model = new IndexShopCollageList();
        $this->user_collage_model = new IndexUserCollage();
        $this->water_model        = new IndexSellingWater();
        $this->profit_model       = new IndexSellingProfit();
        $this->user_model         = new IndexUser();
        $this->collage_model      = new IndexShopCollage();
        $this->refund_model       = new IndexOrderRefund();
        $this->count_model        = new IndexCardCount();
        $this->car_model          = new IndexShopCar();

        $admin_order_model = new \app\shop\model\AdminShopOrder();
        //检测订单
        $admin_order_model->checkOrder($this->_uniacid,$this->_config);
    }
    /**
     * 获取订单列表
     */
    public function orderList(){
        $input = $this->_input;
        if(!empty($input['status'])){
            $dis =  $this->model->orderStatus($input['status']);
        }
        $dis[] = ['uniacid','=',$this->_uniacid];
        if(!empty($input['is_staff'])&&$input['is_staff']==1){
            $dis[] = ['to_uid','=',$this->getUserId()];
        }else{
            $dis[] = ['user_id','=',$this->getUserId()];
        }
        $dis[] = ['status' ,'<>',-1];
        $data  = $this->model->orderList($dis);
        return $this->success($data);
    }


    /**
     *
     * 获取退款订单列表
     */
    public function orderRefundList(){
        $input = $this->_input;
        $dis   =  $this->model->orderRefundStatus($input['status']);
        $dis[] = ['uniacid','=',$this->_uniacid];
        if(!empty($input['is_staff'])&&$input['is_staff']==1){
            $dis[] = ['to_uid','=',$this->getUserId()];
        }else{
            $dis[] = ['user_id','=',$this->getUserId()];
        }
        $dis[] = ['status' ,'<>',-1];
        $data  = $this->model->orderList($dis);
        return $this->success($data);
    }


    /**
     * @return \think\Response
     * 订单详情
     */
    public function orderInfo(){

        $input = $this->_input;

        $data  = $this->model->orderInfo(['id'=>$input['id']]);

        $data['user_img']   = $this->user_model->userImage(['id'=>$data['user_id']]);

        $data['self_text']  = $this->_config['self_text'];
        //商品
        $data['goods_list'] = $this->order_goods_model->where(['order_id'=>$input['id']])->select()->toArray();

        $data['goods_list'] = transImagesOne($data['goods_list'],['cover'],$this->_uniacid);

        $data['over_time_text'] = $data['over_time_text']+$data['create_time'] - time();

        $help_model = new Helppay();
        //代付信息
        $data['help_list'] = $help_model->helpList($data['id']);

        $data['hx_time'] = !empty($data['hx_time'])?date('Y-m-d H:i:s',$data['hx_time']):'';

        $data['hx_user_text'] = lbUserName($data['write_off_id']);

        return $this->success($data);
    }



    /**
     * @author 郑文军
     * @DataTime: 2020/5/27 16:29
     * @功能说明:获取购买数量
     */
    public function getPayNumber(){

        $input = $this->_input;

        $number= $this->order_goods_model->getGoodsNumber(['a.goods_id'=>$input['id'],'b.user_id'=>$this->getUserId()] );
        
        return $this->success(['number'=>$number]);
    }

    /**
     * @return \think\Response
     * @throws \WxPayException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 生成订单并支付
     */

    public function payOrder(){

        $input    = $this->_input;

        $zt_phone = !empty($input[ 'phone' ]) ? $input[ 'phone' ] : '';

        $is_stored = !empty($input[ 'is_stored' ]) ? $input[ 'is_stored' ] : '';

        $zt_name  = !empty($input[ 'name' ]) ? $input[ 'name' ] : '';

        $record_id= !empty($input['coupon_id'])?$input['coupon_id']:'';

        $card     = $this->user_info_model->userInfo(['fans_id'=>$input['staff_id'],'is_staff'=>1]);

        $remarks  = !empty($input['remarks']) ? $input['remarks'] : ''; #下单备注

        if(empty($card)){
            return $this->error('名片没找到');
        }
        if(!is_array($input['goods_info'])){

            return $this->error('商品没找到');
        }
        if(empty($this->getUserId())){

            return $this->error('未找到用户信息');
        }
        //门店id
        $store_id= !empty($input['store_id'])?$input['store_id']:0;
        //自提时间
        $zt_time = !empty($input['zt_time'])?$input['zt_time']:0;
        //获取地址
        $address = $this->getAddress($input['address_id'],$zt_phone,$store_id);

        Db::startTrans();

        $insertOrder   = array(

            'user_id'        => $this->getUserId(),

            'out_trade_no'   => orderCode(),

            'address_id'     => $input['address_id'],

            'freight'        => 0,

            'price'          => 0,

            'total_price'    => 0,

            'uniacid'        => $this->_uniacid,

            'name'           => $address[ 'name' ],

            'sex'            => $address[ 'sex' ],

            'phone'          => $address[ 'phone' ],

            'address'        => $address[ 'address' ],

            'address_detail' => $address[ 'address_detail' ],

            'province'       => $address[ 'province' ],

            'city'           => $address[ 'city' ],

            'area'           => $address[ 'area' ],

            'to_uid'         => $input['staff_id'],

            'create_time'    => time(),

            'update_time'    => time(),

            'zt_name'        => $zt_name,

            'zt_phone'       => $zt_phone,

            'company_id'     => $card['company_id'],
            //门店
            'store_id'       => $store_id,
            //自提时间
            'zt_time'        => $zt_time,

            'remarks'        => $remarks,
            //是否是砍价订单
            'is_bargain'     => !empty($input['bargain_id'])?1:0
        );

        $order_id      = $this->model->orderAdd($insertOrder);

        $total_freight = $pay_price = $init_price = $cost_price =0;

        $discount_goods_model = new DiscountGoods();

        $member_goods_model   = new Goods();

        foreach ($input['goods_info'] as $value){

            $goods = $this->goods_model->goodsInfo(['id'=>$value['goods_id']]);
            //获取运费
            $goods['freight'] = $insertOrder['address_id']==-1?0:$goods[ 'freight' ];

            $spe = $this->spe_price_model->SpePriceFind(['id'=>$value['spe_price_id']]);
            //检查商品状态并且减少库存增加销量
            $err = $this->order_goods_model->checkOrder($input,$spe,$value,$this->getUserId(),$goods);
            //不等于200就报错
            if($err['code']!=200){

                Db::rollback();

                $this->errorMsg($err['msg']);
            }
            //会员商品折扣
            $discount_member = $discount_goods_model->userGoodsDiscount($goods['id'],$this->getUserId(),$this->_uniacid);

            $is_goods_member = $discount_goods_model->isMemberGoods($goods['id'],$this->getUserId(),$this->_uniacid);
            //是不是会员商品
            $is_member       = $discount_goods_model->isMember($goods['is_member'],$this->_uniacid);
            //处理砍价订单
            if(!empty($input['bargain_id'])){

                $bargain_model = new BargainRecord();

                $bar_check = $bargain_model->checkOrder($order_id,$input['bargain_id']);
                //抛出错误信息 并回滚
                if(!empty($bar_check['code'])){

                    Db::rollback();

                    $this->errorMsg($bar_check['msg']);

                }
                //砍价记录详情
                $bar_record = $bargain_model->dataInfo(['id'=>$input['bargain_id']]);

                $spe['price']         = $bar_record['low_price'];

                $spe['spe_name_text'] = $bar_record['spe_name'];

                $goods['name']        = $bar_record['goods_name'];

                $goods['cover']       = $bar_record['goods_cover'];

                $discount_member = 1;

                $is_goods_member = 0;

                $is_member = 0;

            }
            //总运费
            $total_freight += sprintf( '%.2f', $goods[ 'freight' ]);
            //总商品价格
            $pay_price     += sprintf( '%.2f', $spe[ 'price' ] * $value['number']*$discount_member);
            //原价
            $init_price    += sprintf( '%.2f', $spe[ 'price' ] * $value['number']);

            $cost_price    += sprintf( '%.2f', $spe[ 'cost_price' ] * $value['number']);

            $insertItem = array(

                'order_id'     => $order_id,

                'goods_id'     => $goods['id'],

                'name'         => $goods[ 'name' ],

                'cover'        => $goods[ 'cover' ],

                'spe_price_id' => $spe['id'],

                'content'      => $spe['spe_name_text'],

                'number'       => $value['number'],

                'price'        => sprintf( '%.2f', $spe[ 'price' ] * $value['number'] ),

                'cost_price'   => sprintf( '%.2f', $spe[ 'cost_price' ] * $value['number'] ),

                'uniacid'      => $this->_uniacid,
                //是否是会员商品
                'is_member'    => $is_member,
                //商品折扣
                'discounts'    => $discount_member*10,
                //是不是会员商品
                'is_member_goods' => $is_goods_member,
                //会员价
                'member_price' => sprintf( '%.2f', $spe[ 'price' ] * $value['number']*$discount_member ),
            );
            //拼团商品
            if(!empty($input['collage_id'])){

                $collage   =  $this->collage($input['collage_id'],$goods,$value['number'],$input['collage_satrt']);

                $pay_price = sprintf( '%.2f', $value['number'] * $collage['data'][ 'price' ]);

                $init_price = $pay_price;

                $order_insert['type'] = 1;

                $order_insert['collage_id'] = $collage['id'];

                $insertItem['price'] = sprintf( '%.2f', $pay_price);
            }
            //会员订单商品
            $order_insert['is_member'] = $is_member;

            $item_res = $this->order_goods_model->orderGoodsAdd($insertItem);

            if($item_res===false){

                return $this->error('添加订单失败，请重新下单');
            }
            //会员折扣商品对类型
            $member_level = $member_goods_model->getGoodsType($goods['id']);

            if(!empty($member_level)){

                $order_insert['over_time'] = $member_level['type']==1&&$is_member==1?$member_level['over_time']:0;

                $order_insert['level_top'] = $member_level['type']==1&&$is_member==1?0:$member_level['top'];
            }
        }

        $order_insert['freight']     = $total_freight;

        $order_insert['price']       = $init_price;

        $order_insert['cost_price']  = $cost_price;

        $order_insert['member_discount_price'] = round($init_price-$pay_price,2);

        $order_insert['total_price'] = round($order_insert['freight']+$pay_price,2);
        //优惠券抵扣
        if (!empty($record_id)&&empty($input['bargain_id'])) {
            //检查优惠券
            $order_insert = $this->coupon_record_model->checkOrder($record_id,$input,$this->getUserId(),$order_insert,$input['goods_info']);

            if(!empty($order_insert['code'])&&$order_insert['code']==400){

                $this->errorMsg($err['msg']);

            }

        }
        //储值支付
        $order_insert['stored'] = $is_stored==1?$order_insert['total_price']:0;

        $res        = $this->model->orderUpdate(['id'=>$order_id],$order_insert);

        $order_info = $this->model->orderInfo(['id'=>$order_id]);

        if($res===false){

            return $this->error('下单失败，请重新下单');
        }
        //0元支付
        if ( $order_info[ 'total_price' ] == 0 ) {
            //储值支付
            $reslut = new IndexPayResunt($this->app);
            //商城回调
            $reslut->payResunt($order_info);

            $jsApiParameters= '';
            //微信支付
        }elseif($order_info[ 'total_price' ]>0&&$is_stored==0){

            $pay_controller = new IndexWxPay($this->app);

            $user           = $this->getUserInfo();

            $jsApiParameters= $pay_controller->createWeixinPay($this->payConfig(),$user['openid'],$this->_uniacid,"购买商品",['type' => 'PayGoods' , 'out_trade_no' => $order_info['out_trade_no']],$order_info['total_price']);

        }elseif ($order_info[ 'total_price' ]>0&&$is_stored==1){

            $member_model      = new Member();
            //会员信息
            $member = $member_model->memberUpdateInfo(['user_id' => $order_info['user_id'],'uniacid'=>$order_info['uniacid']]);

            if($order_info['stored']>$member['stored']){

                $this->errorMsg('储值不足');
            }

            $jsApiParameters = '';
            //储值支付
            $reslut = new IndexPayResunt($this->app);
            //商城回调
            $reslut->payResunt($order_info);
            //储值记录
            $res = $reslut->orderStoredResult($order_info,3);

            if($res!=1){

                $this->errorMsg('储值不足');

            }

        }

        Db::commit();

       return $this->success(['order' => $order_info,'pay_list' => $jsApiParameters]);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-02-02 11:30
     * @功能说明:下单时候获取商品配送方式
     */
    public function goodsSendStyle(){

        $input = $this->_input;
        //商品配送方式
        $goods_send = $this->order_goods_model->getGoodsSend($input['goods_info']);

        return $this->success($goods_send);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-02-02 09:29
     * @功能说明:下单时候的页面信息
     */
    public function payOrderInfo(){

        $input = $this->_input;

        $total_freight = $total_i_price = $total_integral = $pay_price = $init_price = $cost_price= $goods_num = $member_discount_price = $sale_discount_price=0;

        $integral_model= new Integral();

        $sale_discount = 1;
        //检查积分商城权限
        $i_p = new PermissionIntegral($this->_uniacid);

        $integral_data = [

            'buy_limit'    => 1,

            'discount_add' => 1,
        ];
        //判断积分权限 并且砍价成功后不受积分活动影响
        if($i_p==true&&empty($input['bargain_id'])&&empty($input['collage_id'])){
            //获取积分商城信息(是否必须用积分，是否可以叠加优惠)
            $integral_data = $integral_model->getBuyLimit($input['goods_info']);

            $input['goods_info'] = $integral_model->payOrderInfo($input['goods_info']);
        }

        $input['buy_limit']  = $integral_data['buy_limit'];

        $input['is_integral'] = (!empty($input['is_integral'])||$integral_data['buy_limit']==0)?1:0;
        //是否可以优惠叠加
        $discount_add = $input['is_integral']==1&&$integral_data['discount_add']==0?0:1;

        foreach ($input['goods_info'] as $k=> $value){

            $goods_where['id'] = $value['goods_id'];

            if($input['address_id']==-1){

                $goods_where['is_self'] = 1;

            }else{

                $goods_where['is_send'] = 1;

            }
            //商品信息
            $goods = $this->goods_model->goodsInfo($goods_where);

            if(!empty($goods)){
                //获取运费
                $goods['freight'] = $input['address_id']==-1?0:$goods[ 'freight' ];

                $spe = $this->spe_price_model->SpePriceFind(['id'=>$value['spe_price_id']]);

                $integral_price = isset($value['integral_price'])?$value['integral_price']:$spe['price'];

                $i_price  = $spe['price'] - $integral_price;
                //固定价格活动 拼团 砍价 积分商城等活动
                $atv_data = $this->order_goods_model->payOrderInfoAtv($input,$spe,$goods);

                if(!empty($atv_data['code'])){

                    $this->errorMsg($atv_data['msg']);
                }

                $goods = $atv_data['goods'];

                $spe   = $atv_data['spe'];
                //所有关于折扣的信息 会员折扣、批发价折扣
                $discount_arr = $this->order_goods_model->orderGoodsDiscount($goods,$this->getUserId(),$this->_uniacid,$value,$input,$discount_add);

                if($discount_arr['sale_discount']!=1){

                    $sale_discount = 0;
                }

                $integral = !empty($value['integral'])?$value['integral']:0;
                //商品信息
                $data['list'][$k]=[

                    'price'         => isset($spe['i_goods_price'])?$spe['i_goods_price']:$spe['price'],

                    'i_price'       => isset($value['integral_price'])?$value['integral_price']:0,

                    'spe_name_text' => $spe['spe_name_text'],

                    'name'          => $goods['name'],

                    'cover'         => $goods['cover'],

                    'is_self'       => $goods['is_self'],

                    'is_send'       => $goods['is_send'],

                    'number'        => $value['number'],

                    'goods_id'      => $goods['id'],

                    'spe_price_id'  => $value['spe_price_id'],
                    //是否是会员折扣商品
                    'is_member_discount' => $discount_arr['is_goods_member'],
                    //会员价
                    'member_price'     => round($spe['price']*$discount_arr['member_discount'],2),
                    //是否是批发价商品
                    'is_sale_discount' => $discount_arr['sale_discount']<1?1:0,
                    //批发价
                    'sale_price'       => round($spe['price']*$discount_arr['sale_discount'],2),
                    //积分
                    'integral'         => $integral,
                ];

                $goods_price = isset($spe['i_goods_price'])?$spe['i_goods_price']:$spe[ 'price' ];

                $total_i_price += $i_price* $value['number'];

                $total_integral+= $integral* $value['number'];

                $goods_num     += $value['number'];
                //总运费
                $total_freight += sprintf( '%.2f', $goods[ 'freight' ]);
                //总商品价格
                $pay_price     += sprintf( '%.2f', $spe[ 'price' ] * $value['number']*$discount_arr['member_discount']*$discount_arr['sale_discount']);
                //原价
                $init_price    += sprintf( '%.2f', $goods_price * $value['number']);

                $cost_price    += sprintf( '%.2f', $spe[ 'cost_price' ] * $value['number']);

                $member_discount_price += $spe[ 'price' ] * $value['number']*(1-$discount_arr['member_discount']);

                $sale_discount_price   += $spe[ 'price' ] * $value['number']*(1-$discount_arr['sale_discount']);

            }

        }

        $data['member_discount_price'] = round($member_discount_price,2);

        $data['sale_discount_price']  = round($sale_discount_price,2);

        $data['order_price'] = round($init_price,2);

        $data['freight']     = round($total_freight,2);

        $data['price']       = round($pay_price,2);

        $data['cost_price']  = round($cost_price,2);

        $data['total_price'] = round($data['freight'] + $pay_price,2);

        $data['goods_num']   = $goods_num;
        //总的积分
        $data['total_integral'] = $total_integral;

        $data['total_i_price'] = round($total_i_price,2);
        //是否只能用积分
        $data['buy_limit']    = $integral_data['buy_limit'];
        //积分是否还能用其他营销活动
        $data['discount_add'] = $integral_data['discount_add'];
        //优惠券
        if(!empty($input['coupon_id'])&&$sale_discount==1){

            $coupon_price = $this->coupon_record_model->checkCouponPrice($input['coupon_id'],$this->getUserId(),$pay_price,$input['goods_info']);

        }else{

            $coupon_price = 0;
        }

        $data['coupon_price']= $coupon_price;

        $data['total_price'] = round($data['total_price']-$coupon_price,2);

        return $this->success($data);
    }



    /**
     * @return \think\Response
     * @throws \WxPayException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 生成订单并支付
     */

    public function payOrderV2(){

        $input    = $this->_input;

        $zt_phone = !empty($input[ 'phone' ]) ? $input[ 'phone' ] : '';

        $is_stored= !empty($input[ 'is_stored' ]) ? $input[ 'is_stored' ] : '';

        $zt_name  = !empty($input[ 'name' ]) ? $input[ 'name' ] : '';

        $record_id= !empty($input['coupon_id'])?$input['coupon_id']:'';

        $card     = $this->user_info_model->userInfo(['fans_id'=>$input['staff_id'],'is_staff'=>1]);

        $remarks  = !empty($input['remarks']) ? $input['remarks'] : ''; #下单备注

        if(empty($card)){
            return $this->error('名片没找到');
        }
        if(!is_array($input['goods_info'])){

            return $this->error('商品没找到');
        }
        if(empty($this->getUserId())){

            return $this->error('未找到用户信息');
        }
        //门店id
        $store_id= !empty($input['store_id'])?$input['store_id']:0;
        //自提时间
        $zt_time = !empty($input['zt_time'])?$input['zt_time']:0;
        //获取地址
        $address = $this->getAddress($input['address_id'],$zt_phone,$store_id,$zt_name);
        //检查积分商城权限
        $i_p = new PermissionIntegral($this->_uniacid);

        $integral_data = [

            'buy_limit'    => 1,

            'discount_add' => 1,
        ];

        if($i_p==true&&empty($input['bargain_id'])&&empty($input['collage_id'])){

            $integral_model= new Integral();
            //获取积分商城信息(是否必须用积分，是否可以叠加优惠)
            $integral_data = $integral_model->getBuyLimit($input['goods_info']);

        }
        //如果必须使用积分
        if($integral_data['buy_limit']==0){

            $input['is_integral'] = 1;
        }
        //是否可以优惠叠加
        $discount_add = !empty($input['is_integral'])&&$integral_data['discount_add']==0?0:1;

        Db::startTrans();

        $insertOrder   = array(

            'user_id'        => $this->getUserId(),

            'out_trade_no'   => orderCode(),

            'address_id'     => $input['address_id'],

            'freight'        => 0,

            'price'          => 0,

            'total_price'    => 0,

            'uniacid'        => $this->_uniacid,

            'name'           => $address[ 'name' ],

            'sex'            => $address[ 'sex' ],

            'phone'          => $address[ 'phone' ],

            'address'        => $address[ 'address' ],

            'address_detail' => $address[ 'address_detail' ],

            'province'       => $address[ 'province' ],

            'city'           => $address[ 'city' ],

            'area'           => $address[ 'area' ],

            'to_uid'         => $input['staff_id'],

            'create_time'    => time(),

            'update_time'    => time(),

            'zt_name'        => $zt_name,

            'zt_phone'       => $zt_phone,

            'company_id'     => $card['company_id'],
            //门店
            'store_id'       => $store_id,
            //自提时间
            'zt_time'        => $zt_time,

            'remarks'        => $remarks,
            //是否是砍价订单
            'is_bargain'     => !empty($input['bargain_id'])?1:0
        );

        $order_id      = $this->model->orderAdd($insertOrder);

        $total_freight = $total_i_price = $total_integral = $pay_price = $init_price = $cost_price = $member_discount_price = $sale_discount_price= 0;

        $member_goods_model   = new Goods();

        $sale_discount = 1;

        foreach ($input['goods_info'] as $value){

            $goods_where['id'] = $value['goods_id'];

            if($input['address_id']==-1){

                $goods_where['is_self'] = 1;

            }else{

                $goods_where['is_send'] = 1;

            }
            //商品信息
            $goods = $this->goods_model->goodsInfo($goods_where);

            if(!empty($goods)){

                $bargan_atv_model   = new BargainAtv();
                //获取运费
                $goods['freight'] = $insertOrder['address_id']==-1?0:$goods[ 'freight' ];

                $spe = $this->spe_price_model->SpePriceFind(['id'=>$value['spe_price_id']]);

                $must_atv_spe = $bargan_atv_model->mastAtvSpe($goods['id']);

                if(in_array($spe['id'],$must_atv_spe)&&empty($input['bargain_id'])&&empty($input['collage_id'])&&empty($input['is_integral'])){

                    Db::rollback();

                    $this->errorMsg('该商品不允许原价购买');

                }
                //关于营销活动的信息，主要拼团、砍价 并且会返回处理好的商品信息
                $minus_arr = $this->order_goods_model->doMinusAtv($input,$order_id,$goods,$value['number'],$this->getUserId(),$spe);

                if(!empty($minus_arr['code'])){

                    Db::rollback();

                    $this->errorMsg($minus_arr['msg']);
                }

                $input['integral_id'] = $minus_arr['integral_atv_id'];
                //所有关于折扣的信息 会员折扣、批发价折扣
                $discount_arr = $this->order_goods_model->orderGoodsDiscount($goods,$this->getUserId(),$this->_uniacid,$value,$input,$discount_add);

                if($discount_arr['sale_discount']!=1){

                    $sale_discount = 0;
                }
                //检查商品状态并且减少库存增加销量
                $err = $this->order_goods_model->checkOrder($input,$spe,$value,$this->getUserId(),$goods);
                //不等于200就报错
                if($err['code']!=200){

                    Db::rollback();

                    $this->errorMsg($err['msg']);
                }
                //是否是拼团商品
                $order_insert['type'] = $minus_arr['type'];
                //拼团id没有就是0
                $order_insert['collage_id'] = $minus_arr['collage_id'];

                $total_integral+= $minus_arr['integral']*$value['number'];

                $total_i_price += $minus_arr['i_price']*$value['number'];
                //总运费
                $total_freight += sprintf( '%.2f', $goods[ 'freight' ]);
                //总商品价格
                $singe_pay_price= sprintf( '%.2f', $minus_arr[ 'price' ] * $value['number']*$discount_arr['member_discount']*$discount_arr['sale_discount']);

                $pay_price     +=$singe_pay_price;
                //原价
                $init_price    += !empty($minus_arr['i_record_id'])?sprintf( '%.2f', $minus_arr[ 'goods_price' ] * $value['number']):sprintf( '%.2f', $minus_arr[ 'price' ] * $value['number']);

                $cost_price    += sprintf( '%.2f', $spe[ 'cost_price' ] * $value['number']);

                $member_discount_price += $minus_arr[ 'price' ] * $value['number']*(1-$discount_arr['member_discount']);

                $sale_discount_price   += $minus_arr[ 'price' ] * $value['number']*(1-$discount_arr['sale_discount']);

                $insertItem = array(

                    'order_id'     => $order_id,

                    'goods_id'     => $goods['id'],

                    'version'      => 1,

                    'name'         => $minus_arr[ 'name' ],

                    'cover'        => $minus_arr[ 'cover' ],

                    'spe_price_id' => $spe['id'],

                    'content'      => $minus_arr['spe_name_text'],

                    'number'       => $value['number'],
                    //商品现价
                    'price'        => !empty($minus_arr['i_record_id'])?sprintf( '%.2f', $minus_arr[ 'goods_price' ] * $value['number'] ):round($minus_arr[ 'price' ] * $value['number'],2),

                    'pay_price'    => $singe_pay_price,
                    //商品原价
                    'cost_price'   => sprintf( '%.2f', $spe[ 'cost_price' ] * $value['number'] ),

                    'uniacid'      => $this->_uniacid,
                    //是否是会员商品
                    'is_member'    => $discount_arr['is_member'],
                    //商品折扣
                    'discounts'    => $discount_arr['member_discount']*10,
                    //是不是会员商品
                    'is_member_goods'=> $discount_arr['is_goods_member'],
                    //会员价
                    'member_price'   => sprintf( '%.2f', $minus_arr[ 'price' ] * $value['number']*$discount_arr['member_discount'] ),
                    //是否是批发价商品
                    'is_sale_goods'  => $discount_arr['sale_discount']<1?1:0,
                    //批发价
                    'sale_price'     => round($minus_arr['price']* $value['number']*$discount_arr['sale_discount'],2),

                    'integral_id'    => $minus_arr['integral_atv_id'],

                    'integral'       => $minus_arr['integral'],

                    'i_record_id'    => $minus_arr['i_record_id'],

                    'integral_goods_id'=> $minus_arr['integral_goods_id'],
                );
                //会员订单商品
                $order_insert['is_member'] = $discount_arr['is_member'];

                $item_res = $this->order_goods_model->orderGoodsAdd($insertItem);

                if($item_res===false){

                    return $this->error('添加订单失败，请重新下单');
                }
                //处理折扣信息
                $order_goods_id = $this->order_goods_model->getLastInsID();

                $discount_arr['i_record_id'] = $minus_arr['i_record_id'];

                $this->order_goods_model->doDiscount($discount_arr,$order_goods_id);
                //会员折扣商品对类型
                $member_level = $member_goods_model->getGoodsType($goods['id']);

                if(!empty($member_level)){

                    $order_insert['over_time'] = $member_level['type']==1&&$discount_arr['is_member']==1?$member_level['over_time']:0;

                    $order_insert['level_top'] = $member_level['type']==1&&$discount_arr['is_member']==1?0:$member_level['top'];
                }
            }

        }

        $order_insert['integral']    = $total_integral;
        //积分抵扣多少钱
        $order_insert['i_price']     = round($total_i_price,2);

        $order_insert['freight']     = $total_freight;

        $order_insert['price']       = $init_price;

        $order_insert['cost_price']  = $cost_price;
        //会员抵扣价
        $order_insert['member_discount_price'] = round($member_discount_price,2);
        //批发价抵扣金额
        $order_insert['sale_discount_price']   = round($sale_discount_price,2);

        $order_insert['total_price'] = round($order_insert['freight']+$pay_price,2);
        //优惠券抵扣
        if (!empty($record_id)&&empty($input['bargain_id'])&&$sale_discount==1){

            $goods_info   = $this->order_goods_model->where(['order_id'=>$order_id])->select()->toArray();
            //检查优惠券
            $order_insert = $this->coupon_record_model->checkOrderV2($record_id,$input,$this->getUserId(),$order_insert,$goods_info);

            if(!empty($order_insert['code'])&&$order_insert['code']==400){

                Db::rollback();

                $this->errorMsg($err['msg']);

            }

        }
        //使用了积分
        if(!empty($total_integral)){

            $member_model      = new Member();
            //会员信息
            $member = $member_model->memberUpdateInfo(['user_id' => $this->getUserId(),'uniacid'=>$this->_uniacid]);

            if($total_integral>$member['integral']){

                $this->errorMsg('积分不足');
            }

        }
        //储值支付
        $order_insert['stored'] = $is_stored==1?$order_insert['total_price']:0;

        $res        = $this->model->orderUpdate(['id'=>$order_id],$order_insert);

        $order_info = $this->model->orderInfo(['id'=>$order_id]);

        if($res===false){

            return $this->error('下单失败，请重新下单');
        }
        //代付就不支付
        if(!empty($input['help_order'])&&$order_info[ 'total_price' ] >0){

            if(!empty($total_integral)&&$total_integral>0){

                $this->errorMsg('积分抵扣不能代付');

            }

            Db::commit();

            return $this->success(['order' => $order_info ]);

        }
        //0元支付
        if ( $order_info[ 'total_price' ] == 0 ) {
            //储值支付
            $reslut = new IndexPayResunt($this->app);
            //商城回调
            $reslut->payResunt($order_info);

            $jsApiParameters= '';
            //微信支付
        }elseif($order_info[ 'total_price' ]>0&&$is_stored==0){

            $pay_controller = new IndexWxPay($this->app);

            $user           = $this->getUserInfo();

            $jsApiParameters= $pay_controller->createWeixinPay($this->payConfig(),$user['openid'],$this->_uniacid,"购买商品",['type' => 'PayGoods' , 'out_trade_no' => $order_info['out_trade_no']],$order_info['total_price']);

        }elseif ($order_info[ 'total_price' ]>0&&$is_stored==1){

            $member_model      = new Member();
            //会员信息
            $member = $member_model->memberUpdateInfo(['user_id' => $order_info['user_id'],'uniacid'=>$order_info['uniacid']]);

            if($order_info['stored']>$member['stored']){

                $this->errorMsg('储值不足');
            }

            $jsApiParameters = '';
            //储值支付
            $reslut = new IndexPayResunt($this->app);
            //商城回调
            $reslut->payResunt($order_info);
            //储值记录
            $res = $reslut->orderStoredResult($order_info,3);

            if($res!=1){

                $this->errorMsg('储值不足');

            }

        }

        Db::commit();

        return $this->success(['order' => $order_info,'pay_list' => $jsApiParameters]);

    }

    /**
     * @author chenniang
     * @DataTime: 2020-09-17 13:39
     * @功能说明:会员信息
     */
    public function memberInfo(){

        $member_model      = new Member();
        //会员信息
        $member = $member_model->memberUpdateInfo(['user_id' => $this->getUserId(),'uniacid'=>$this->_uniacid]);

        return $this->success($member);
    }


    /**
     * @param $collage_id
     * @param $goods_info
     * @param $number
     * @param $is_start
     * 拼团
     */
    public function collage($collage_id,$goods_info,$number,$is_start){
        if($is_start==1){
            $data = $this->startCollage($collage_id,$goods_info,$number);
        }else{
            $data = $this->joinCollage($collage_id,$number);
        }
        return $data;
    }

    /**
     * @param $collage_id
     * @param $number
     * @return array|\think\Model|\think\Response|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 加入拼团
     */
    public function joinCollage($collage_id,$number){

        $collage = $this->collage_list_model->collageInfo(['id'=> $collage_id]);

        if(empty($collage)){

            $this->errorMsg('拼团未找到');
        }

        $collage2 = $this->collage_model->collageInfo([ 'id' => $collage[ 'collage_id' ]]);

        if ( !$collage2 || $number < $collage2[ 'number' ] ) {

            $this->errorMsg('拼团信息错误');
        }

        $left_number = $collage['left_number'];

        if($left_number<=0){

            $this->errorMsg('拼团人数已满');
        }

        $this->checkCollageLimit($collage2);

        $this->collage_list_model->collageUpdate([ 'id' => $collage_id ],['left_number'=>Db::raw('left_number-1')] );

        $insert_data = [

            'user_id'    => $this->getUserId(),

            'collage_id' => $collage_id,

            'uniacid'    => $this->_uniacid
        ];

        $this->user_collage_model->collageAdd($insert_data);

        $re_data['data'] = $collage2;

        $re_data['id']   = $collage_id;

        return $re_data;
    }
    /**
     * User: chenniang
     * Date: 2019-09-19 17:38
     * @return \think\Response
     * descption:未支付增加拼团人数
     */
    public function refundCollage(){
        $input = $this->_input;
        $this->collage_list_model->collageUpdate([ 'id' => $input['id'] ],['left_number'=>Db::raw('left_number+1')] );
        return $this->success(true);
    }
    /**
     * @param $collage_id
     * @param $goods_info
     * @param $number
     * @return array|\think\Model|\think\Response|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 发起拼团
     */

    public function startCollage($collage_id,$goods_info,$number){

        $collage = $this->collage_model->collageInfo(['goods_id' => $goods_info['id'], 'id'=> $collage_id]);

        if(empty($collage)){

            $this->errorMsg('拼团未找到');
        }
        if ($number < $collage[ 'number' ]) {

            $this->errorMsg('拼团信息错误');

        }
        $this->checkCollageLimit($collage);

        $insertCollageListData = array(
            'user_id'     => $this->getUserId(),
            'goods_id'    => $goods_info['id'],
            'collage_id'  => $collage_id,
            'name'        => $goods_info[ 'name' ],
            'cover'       => $goods_info[ 'cover' ],
            'number'      => $collage[ 'people' ],
            'left_number' => $collage[ 'people' ] - 1,
            'price'       => $collage[ 'price' ],
            'uniacid'     => $this->_uniacid,
        );
        $collage_list_id = $this->collage_list_model->collageAdd($insertCollageListData);

        if ( !$collage_list_id ) {

            $this->errorMsg('拼团失败');
        }
        $insert_data = [

            'user_id'     => $this->getUserId(),

            'collage_id'  => $collage_list_id,

            'uniacid'     => $this->_uniacid
        ];
        $this->user_collage_model->collageAdd($insert_data);

        $re_data['data'] = $collage;

        $re_data['id']   = $collage_list_id;

        return $re_data;
    }
    /**
     * @param $collage
     * @return bool|\think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 检查是否参加过拼团
     */
    public function checkCollageLimit($collage){

        if ($collage['limit']) {

            $collage_dis = [

                'uniacid'    => $this->_uniacid,

                'collage_id' => $collage['id']
            ];
            //获取这个拼团活动所有的拼团id
            $collage_id = $this->collage_list_model->where($collage_dis)->where('collage_status','<>',4)->column('id');

            if (!empty($collage_id)){

                $where[] = ['collage_id','in',$collage_id];
                //出去拼团失败的
                $where[] = ['collage_status','<>',4];

                $where[] = ['user_id','=',$this->getUserId()];
                //查找自己是有插件过拼团
                $check = $this->user_collage_model->where($where)->find();

                if(!empty($check)){

                    $this->errorMsg('已经参加过此拼团, 不能重复参加');
                }

            }

        }
        return true;
    }


    /**
     *
     * 重新支付
     */
    public function rePayOrder(){

        $input = $this->_input;

        $order = $this->model->orderInfo(['id'=>$input['id'],'pay_status'=>0]);

        if(empty($order)){

            return $this->error('订单未找到，请重新下单');
        }

        if($order['status_text'] != 1){

            $this->errorMsg('订单已过期/或已支付');

        }
        //使用了积分
        if($order['integral']>0){

            $member_model      = new Member();
            //会员信息
            $member = $member_model->memberUpdateInfo(['user_id' => $this->getUserId(),'uniacid'=>$this->_uniacid]);

            if($order['integral']>$member['integral']){

                $this->errorMsg('积分不足');
            }

        }

        if($order['type']==1){
            $colleage = $this->collage_list_model->collageInfo(['id'=>$order['collage_id']]);
            if(empty($colleage)){
                return $this->error('not data');
            }
            if($colleage['left_number']<=0){
                return $this->error('拼团人数已满');
            }
            if($colleage['collage_status']!=1&&$colleage['collage_status']!=0){
                return $this->error('拼团已失效或拼团已完成');
            }
            $collage_user_dis[] = ['user_id'       ,'=' , $order['user_id']];
            $collage_user_dis[] = ['collage_status','in', [1,2,3]];
            $collage_user_dis[] = ['collage_id'    ,'=' , $order['collage_id']];
            $user_collage  = $this->user_collage_model->where($collage_user_dis)->field('id')->find();
            if(!empty($user_collage)){
                return $this->error('你已经参加过该拼团了');
            }
            $this->collage_list_model->collageUpdate([ 'id' => $order['collage_id'] ],['left_number'=>Db::raw('left_number-1')] );
        }

        $pay_controller = new IndexWxPay($this->app);

        $user           = $this->getUserInfo();

        $jsApiParameters= $pay_controller->createWeixinPay($this->payConfig(),$user['openid'],$this->_uniacid,"购买商品",['type' => 'PayGoods' , 'out_trade_no' => $order['out_trade_no']],$order['total_price']);

        return $this->success(['order' => $order,'pay_list' => $jsApiParameters]);
    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-21 13:52
     * @功能说明:代付（目前单人）
     */

    public function helpPay(){

        $input = $this->_input;

        $order = $this->model->orderInfo(['id'=>$input['order_id']]);

        if(empty($order)){

            $this->errorMsg('订单未找到');
        }

        if($order['status_text'] != 1){

            $this->errorMsg('订单已过期/或已支付');

        }

        $help_model = new Helppay();

        $dis = [

            'user_id' => $this->getUserId(),

            'order_id'=> $input['order_id']
        ];

        $info = $help_model->dataInfo($dis);

        if(empty($info)){

            $info=[

                'uniacid'    => $this->_uniacid,

                'order_id'   => $input['order_id'],

                'user_id'    => $this->getUserId(),

                'order_code' => orderCode(),

                'pay_price'  => $order['total_price'],

                'staff_id'   => $order['to_uid']

            ];

            $help_model->dataAdd($info);
        }

        $user           = $this->getUserInfo();

        $pay_controller = new IndexWxPay($this->app);

        $jsApiParameters= $pay_controller->createWeixinPay($this->payConfig(),$user['openid'],$this->_uniacid,"代付",['type' => 'helppay' , 'out_trade_no' => $info['order_code']],$order['total_price']);

        $info['collage_id'] = $order['collage_id'];

        return $this->success(['order' => $info,'pay_list' => $jsApiParameters]);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-21 15:10
     * @功能说明:删除支付的锁
     */
    public function delStock(){

        $input = $this->_input;

        $key   = 'helppay'.$this->_uniacid.'-'.$input['order_id'];

        decCache($key,1,1234);

        return $this->success(true);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-23 09:37
     * @功能说明:代付订单信息
     */
    public function helpOrderInfo(){

        $input = $this->_param;

        $config= $this->_config;

        $user_model = new IndexUser();

        $help_model = new Helppay();

        $order_overtime  = !empty($config['order_overtime'])?$config['order_overtime']:1800;

        //$data = Db::name('longbing_card_shop_order')->where(['id'=>$input['order_id']])->field('id,create_time,pay_status,order_status,user_id,total_price')->find();

        $data = $this->model->orderInfo(['id'=>$input['order_id']]);

        //过期时间
        $data['over_time'] = $data['create_time']+$order_overtime-time();

        $data['over_time'] = $data['status_text']==1&&$data['over_time']>0?$data['over_time']:0;

        $data['nickName']  = $user_model->where(['id'=>$data['user_id']])->value('nickName');

        $data['avatarUrl'] = $user_model->where(['id'=>$data['user_id']])->value('avatarUrl');
        //代付信息
        $data['help_list'] = $help_model->helpList($data['id']);

        return $this->success($data);

    }




    /**
     * @param $address_id
     * @param $phone
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取地址
     */
    public function getAddress($address_id,$phone,$store_id=0,$name = ''){
        if ($address_id != -1 ) {
            $address = $this->address_model->addressInfo(['id'=>$address_id,'user_id'=>$this->getUserId()]);
            if (empty( $address)) {
                $this->errorMsg('地址信息未找到');
            }
        } else {

            $user_info                   = $this->getUserInfo();
            $address[ 'name' ]           = !empty($name)?$name: $user_info[ 'nickName'] ;
            $address[ 'sex' ]            = '无';
            $address[ 'phone' ]          = $phone;

            if($store_id==0){
                $address[ 'address' ]        = '自提';
                $address[ 'address_detail' ] = '自提';
                $address[ 'province' ]       = '自提';
                $address[ 'city' ]           = '自提';
                $address[ 'area' ]           = '自提';
            }else{

                $store_model = new \app\shop\model\IndexStore();
                //门店
                $store       = $store_model->storeInfo(['id'=>$store_id]);

                if(empty($store)){

                    $this->errorMsg('地址信息未找到');
                }
                //门店
                $address[ 'address' ]        = $store['title'];
                //地址
                $address[ 'address_detail' ] = $store['address'];
                //省
                $address[ 'province' ]       = $store['province'];
                //市
                $address[ 'city' ]           = $store['city'];
                //区
                $address[ 'area' ]           = $store['area'];
            }

        }
        return $address;
    }


    /**
     * @author chenniang
     * @DataTime: 2022-02-11 17:22
     * @功能说明:取消订单
     */
    public function cancelOrder(){
        $input = $this->_input;
        $dis[] = ['id','=',$input['id']];
        $dis[] = ['pay_status','=',0];
        $dis[] = ['user_id','=',$this->getUserId()];
        $order = $this->model->orderInfo($dis);
        if(empty($order)){
            return $this->error('订单未找到或订单已支付');
        }
        Db::startTrans();
        $res = $this->model->orderUpdate($dis,['order_status' => 1]);
        if(!$res){
            return $this->error('取消订单失败');
        }
        if($order['record_id']) {

            $this->coupon_record_model->recordUpdate(['id' => $order['record_id']],['status' => 1]);
        }

        if ($order['type'] == 1) {

            $check = $this->collage_list_model->collageInfo(['id' => $order['collage_id']]);

            if ($check) {

                if ($check['user_id'] == $this->getUserId()) {

                    $this->collage_list_model->collageDel(['id' => $order['collage_id']]);

                }else{

//                    $this->collage_list_model->collageUpdate(['id' => $order['collage_id']],['left_number'=>Db::raw("left_number+1")]);
                }

                $this->user_collage_model->collageDel(['collage_id' => $order['collage_id'],'user_id' => $this->getUserId()]);

            }

        }
        //砍价订单 如果超时需要改变砍价记录的状态
        if($order['is_bargain']==1){

            $bargain_model = new BargainRecord();

            $bargain_model->dataUpdate(['order_id'=>$order['id']],['status'=>4]);
        }

        $order_model = new \app\shop\model\AdminShopOrder();
        //加库存减销量
        $res = $order_model->refundStock($order['id']);

        if($res==0){

            Db::rollback();

            $this->errorMsg('取消失败');
        }

        Db::commit();
        return $this->success(true);
    }


    /**
     * 收货
     */
    public function endOrder(){
        $input = $this->_input;
        $dis[] = ['uniacid','=',$this->_uniacid];
        $dis[] = ['id','=',$input['id']];
        $dis[] = ['pay_status','=',1];
        $dis[] = ['order_status','=',2];
        $dis[] = ['user_id','=',$this->getUserId()];
        $order = $this->model->orderInfo($dis);
        if(empty($order)){
            return $this->error('订单未找到');
        }

        if($order['refund_status']==1){

            return $this->error('该订单正在申请退款');

        }
        Db::startTrans();
        $result = $this->model->orderUpdate($dis,['order_status' => 3]);
        if(!$result){
            return $this->error('收货失败');
        }
        if ($order['type'] == 1) {

            $c_dis[]  = ['collage_id'  ,'=', $order['collage_id']];

            $c_dis[]  = ['order_status','>', 2];

            $count    = $this->model->orderCount($c_dis);

            $collage  = $this->collage_list_model->collageInfo(['id' => $order['collage_id']]);

            if ($collage['number'] && $collage['number'] == $count) {

                $this->collage_list_model->collageUpdate(['id' => $order['collage_id']],['collage_status' => 3]);
            }
        }
        $this->profitUpdate($order);
        //会员模型
        $member_model = new Member();
        //结算会员的商品的权益
        $member_model->updateMember($order);
        Db::commit();
        return $this->success(true);
    }

    /**
     *
     * 核销
     */

    public function orderHx(){
        $input = $this->_input;
        if(empty($this->getUserId())){
            return $this->error('未获取到用户信息');
        }
        $order = $this->model->orderInfo(['id'=>$input['id']]);

        if($order['refund_status']!=0){

            return $this->error('订单已申请退款');

        }
        if (!$order){

            return $this->error('没有找到订单');
        }

        if ($order['pay_status'] != 1 ) {

            return $this->error('订单未支付, 无法核销');
        }
        if ($order['order_status'] == 1 ) {

            return $this->error('订单已取消, 无法核销');
        }
        if ($order['order_status'] > 2 ) {
            return $this->error('订单已完成, 无法核销');
        }

        if (empty($this->_config['order_pwd'])) {

            return $this->error('后台没有设置核销密码');
        }
        if ($input['pwd'] != $this->_config['order_pwd']) {

            return $this->error('核销密码错误');
        }
        Db::startTrans();

        $res = $this->model->orderUpdate(['id'=>$input['id']],['order_status'=>3,'write_off_id'=>$this->getUserId(),'hx_time'=>time()]);

        if($res===false){
            return $this->error('核销失败');
        }
        $this->profitUpdate($order);
        //会员模型
        $member_model = new Member();
        //结算会员的商品的权益
        $member_model->updateMember($order);

        $insertData = array(
            'user_id' => $order['user_id'],
            'to_uid'  => $order['to_uid'],
            'sign'    => 'view',
            'type'    => 20,
            'uniacid' => $this->_uniacid,
            'target'  => $order['id'],
        );
        $insert_id = $this->count_model->countAdd($insertData);
        $push_data = array(
            'action'  => 'longbingSendWxServiceNotice',
            'event'   => 'longbingSendWxServiceNotice',
            'count_id'=> $insert_id
        );
        publisher(json_encode($push_data ,true));
        Db::commit();
        return $this->success(true);
    }
    /**
     * @param $order
     * 修改佣金
     */
    public function profitUpdate($order){
        $list = $this->water_model->where(['order_id' => $order['id'], 'waiting' => 1])->select();
        if(!empty($list)){
            foreach ($list as $index => $item) {
                $money = $item['price'] * $item['extract'] / 100;
                if($item['selling_type']==1){

                    $money = $item[ 'extract_cash' ];
                }
                $money = sprintf("%.2f", $money);

                $profit= $this->profit_model->profitInfo(['user_id' => $item['user_id']]);
                if ($profit) {
                    if ($profit['waiting'] >= $money) {
                        $waiting      = $profit['waiting'] - $money;
                        $total_profit = $profit['total_profit'] + $money;
                        $profit_money = $profit['profit'] + $money;
                        $waiting      = sprintf("%.2f", $waiting);
                    } else {
                        $waiting      = 0;
                        $money        = $profit['waiting'];
                        $total_profit = $profit['total_profit'] + $profit['waiting'];
                        $profit_money = $profit['profit'] + $profit['waiting'];
                    }
                    $total_profit = sprintf("%.2f", $total_profit);
                    $profit_money = sprintf("%.2f", $profit_money);
                    $this->profit_model->profitUpdate(['id' => $profit['id']],['waiting' => $waiting, 'total_profit' => $total_profit, 'profit' => $profit_money]);
                    $this->user_model->userUpdate(['id' => $item['source_id']],['create_money'=>Db::raw("create_money+$money")]);
                }
                $res  = $this->water_model->waterUpdate(['id' => $item['id'], 'waiting' => 1],['waiting' => 2]);
            }
        }

        return true;
    }

    /**
     * User: chenniang
     * Date: 2019-09-18 17:41
     * @return \think\Response
     * descption:申请退款
     */
    public function orderRefund(){

        $input = $this->_input;

        $res   = $this->refundApi($input['id']);

        return $this->success(true);
    }

    /**
     *
     * 取消退款
     */
    public function cancelRefund(){
        $input = $this->_input;
        $dis[] = ['uniacid','=',$this->_uniacid];
        $dis[] = ['user_id','=',$this->getUserId()];
        $dis[] = ['id','=',$input['id']];
        $info = $this->model->orderInfo($dis);
        if (!$info) {
            return $this->error('订单未找到');
        }
        if ( $info[ 'pay_status' ] == 0 ) {
            return $this->error('订单未付款');
        }
        if ( $info[ 'pay_status' ] == 2 ) {
            return $this->error('订单已退款');
        }
        if ( $info[ 'order_status' ] == 3 ) {
            return $this->error('订单已完成无法退款');
        }

//        if ( $info[ 'total_price' ] == 0 ) {
//            return $this->error('订单金额为0');
//        }
        if ( $info[ 'refund_status' ] != 1 ) {
            return $this->error('该订单未处于申请退款中');
        }

        $this->refund_model->where([ 'order_id' => $input['id']])->delete();
        $this->model->orderUpdate($dis,[ 'refund_status' => 0 ]);
        $insertData = array(
            'user_id' => $info[ 'user_id' ],
            'to_uid'  => $info[ 'to_uid' ],
            'sign'    => 'view',
            'type'    => 22,
            'uniacid' => $this->_uniacid,
            'target'  => $info[ 'id' ],
        );
        $insert_id = $this->count_model->countAdd($insertData);
        $push_data = array(
            'action'  => 'longbingSendWxServiceNotice',
            'event'   => 'longbingSendWxServiceNotice',
            'count_id'=> $insert_id
        );
        publisher(json_encode($push_data ,true));
        return $this->success(true);

    }


    /**
     * User: chenniang
     * Date: 2019-09-12 20:13
     * @param $id
     * @return int|string
     * descption:退款api
     */
    public function refundApi($id){
        $dis[] = ['uniacid','=',$this->_uniacid];
        $dis[] = ['user_id','=',$this->getUserId()];
        $dis[] = ['id','=',$id];
        $info = $this->model->orderInfo($dis);

        if ( !$info ) {
            $this->errorMsg('订单未找到');
        }

        if ( $info[ 'pay_status' ] == 0 ) {
            $this->errorMsg('订单未付款');
        }

        if ( $info[ 'pay_status' ] == 2 ) {
            $this->errorMsg('订单已退款');
        }

        if ( $info[ 'order_status' ] == 3 ) {

            $this->errorMsg('订单已完成无法退款');

        }

        if ( $info[ 'total_price' ] == 0&&$info['integral']<=0 ) {

            $this->errorMsg('订单金额为0, 无需申请退款');
        }
        if ( $info[ 'refund_status' ] != 0 ) {

            return $this->error('该订单已经申请');
        }
        $insertData = array(

            'order_id' => $id,

            'uniacid'  => $this->_uniacid,

            'status'   => 1,

            'stored'   => $info['stored'],

            'integral' => $info['integral'],
        );

        $refund_id = $this->refund_model->orderAdd($insertData);

        $dis[] = ['refund_status','=',0];

        $res = $this->model->orderUpdate($dis,[ 'refund_status' => 1 ]);
        //如果失败
        if($res!=1){

            return $this->error('申请失败');
        }
        $insertData = array(
            'user_id' => $info[ 'user_id' ],
            'to_uid'  => $info[ 'to_uid' ],
            'sign'    => 'view',
            'type'    => 21,
            'uniacid' => $this->_uniacid,
            'target'  => $info[ 'id' ]
        );
        $insert_id = $this->count_model->countAdd($insertData);
        $push_data = array(
            'action'  => 'longbingSendWxServiceNotice',
            'event'   => 'longbingSendWxServiceNotice',
            'count_id'=> $insert_id
        );

        publisher(json_encode($push_data ,true));

        return $refund_id;

    }
    /**
     * User: chenniang
     * Date: 2019-09-12 19:45
     * @return \think\Response
     * descption:退款
     */
    public function refundMoney(){

        $id  = $this->_input['id'];

        $refund_model = new \app\shop\model\AdminShopOrderRefund();

        Db::startTrans();
        //申请退款
        $res = $this->refundApi($id);
        //退款
        $res = $refund_model->orderRefundApi($res,0,$this->app,$this->payConfig());

        if(!empty($res['code'])){

            $this->errorMsg($res['msg']);
        }
        Db::commit();

        return $this->success(true);
    }


    /**
     * User: chenniang
     * Date: 2019-09-18 15:55
     * @return void
     * descption:获取订单二维码
     */
    public function orderQr(){
        $input = $this->_param;
        $order = $this->model->orderInfo(['id'=>$input['id']]);
        if(empty($order)){
            return $this->error('not data');
        }
        if ($order[ 'pay_status' ] != 1 || $order[ 'order_status' ] != 0 || $order[ 'address_id' ] != -1) {
            return $this->error('status is error');
        }
        $order_qr = getCache($input['id'].'-'.'order_qr',$this->_uniacid);
        if(empty($order_qr)){
            $data     = longbingCreateWxCode($this->_uniacid,$input,'shop/pages/order/hexiao');
            if(isset($data['qr_path'])) $data = transImagesOne($data ,['qr_path'] ,$this->_uniacid);
            $order_qr = $data['qr_path'];
            setCache($input['id'].'-'.'order_qr',$order_qr,86400,$this->_uniacid);
        }
        return $this->success($order_qr);
    }

    /**
     * @author chenniang
     * @DataTime: 2019-12-27 16:57
     * @功能说明:返回模版id
     */
    public function getTmplList(){
        $tmpl_model = new TmplConfig();
        $dis[] = ['uniacid','=',$this->_uniacid];
        $data  = $tmpl_model->tmplIdList($dis);
        return $this->success($data);
    }


    /**
     * @author chenniang
     * @DataTime: 2021-04-14 15:16
     * @功能说明:快递信息
     */
    public function orderExpressInfo(){

        $input = $this->_param;

        $update= !empty($input['update'])?1:0;

        $express_model = new ExpressOrder();

        $order = $express_model->expressInfo($input['order_id'],$this->_uniacid,$update);

        return $this->success($order);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-23 17:15
     * @功能说明:代付配置信息
     */
    public function helpPayConfig(){

        $config_model = new HelppayConfig();

        $data = $config_model->dataInfo(['uniacid'=>$this->_uniacid]);

        return $this->success($data);

    }

}
